$watchCollection
( type in module ng
)
Shallow watches the properties of an object and fires whenever any of the properties change
(for arrays this implies watching the array items, for object maps this implies watching the properties).
If a change is detected the listener
callback is fired.
obj
collection is observed via standard $watch operation and is examined on every call to $digest() to
see if any items have been added, removed, or moved.listener
is called whenever anything within the obj
has changed. Examples include adding new items
into the object or array, removing and moving items around.$scope.names = ['igor', 'matias', 'misko', 'james']; $scope.dataCount = 4; $scope.$watchCollection('names', function(newNames, oldNames) { $scope.dataCount = newNames.length; }); expect($scope.dataCount).toEqual(4); $scope.$digest(); //still at 4 ... no changes expect($scope.dataCount).toEqual(4); $scope.names.pop(); $scope.$digest(); //now there's been a change expect($scope.dataCount).toEqual(3);
Scope#$watchCollection(obj, listener);
obj – {string|Function(scope)} –
Evaluated as expression. The expression value
should evaluate to an object or an array which is observed on each
$digest
cycle. Any shallow change within the collection will trigger
a call to the listener
.
listener – {function(newCollection, oldCollection, scope)} –
a callback function that is fired with both
the newCollection
and oldCollection
as parameters.
The newCollection
object is the newly modified data obtained from the obj
expression and the
oldCollection
object is a copy of the former collection data.
The scope
refers to the current scope.
{function()}
– Returns a de-registration function for this listener. When the de-registration function is executed then the internal watch operation is terminated.